package com.dream21th.generate.util;

import com.dream21th.generate.dto.GenerateDTO;
import com.dream21th.generate.dto.MiddleDTO;
import com.dream21th.generate.dto.MysqlDTO;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @Auther: hp
 * @Date: 2019/6/11 22:04
 * @Description:
 */
public class GenerateCodeUtils {

     public static void generateCode(MysqlDTO mysqlDTO,String tableName) throws SQLException, IOException, TemplateException {
         mysqlDTO.setTableName(tableName);
         String url=mysqlDTO.getUrl();
         String db=url.substring(url.lastIndexOf("/")+1,url.indexOf("?"));
         String dateBase=Objects.nonNull(mysqlDTO.getDataBase())?mysqlDTO.getDataBase():db;
         mysqlDTO.setDataBase(dateBase);
         GenerateDTO com = GenerateDTO.builder().packageName(mysqlDTO.getPackageName()).author(mysqlDTO.getAuthor()).mysql(mysqlDTO).build();

         com.setFileds(queryTableInfo(mysqlDTO));

         FreeMakeUtils.generate(com);

     }

    public static void generateCode(MysqlDTO mysqlDTO) {
         if(Objects.isNull(mysqlDTO.getTableNames()) || mysqlDTO.getTableNames().length==0){
             throw new RuntimeException("请输入表名");
         }
        String[] tableNames = mysqlDTO.getTableNames();
        Arrays.stream(tableNames).forEach(tablename -> {
            try {
                generateCode(mysqlDTO, tablename);
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        });
    }


    private static List<MiddleDTO> queryTableInfo(MysqlDTO dto) throws SQLException {
        DBUtils dbUtils = new DBUtils();
        dbUtils.queryTableInfo(dto);
        ResultSet rs = dbUtils.getRs();

        List<MiddleDTO> lists = new ArrayList<MiddleDTO>();
        while (rs.next()) {
            String column_name = rs.getString("COLUMN_NAME");
            String data_type = TypeTranferUtils.dbToJava(rs.getString("DATA_TYPE"));
            String is_nullable = rs.getString("IS_NULLABLE");
            String column_key = rs.getString("COLUMN_KEY");
            String column_comment = rs.getString("COLUMN_COMMENT");
            MiddleDTO build = MiddleDTO.builder().columnName(column_name).dataType(data_type).isNullable(is_nullable).columnKey(column_key).
                    columnComment(column_comment).javaColumnName(TypeTranferUtils.dbColumnToJava(column_name)).build();
            lists.add(build);
        }
        dbUtils.closed();
        return lists;
    }
}
